<template>
  <view class="search-result-page">
    <view class="top-space"></view>
    
    <!-- 搜索头部 -->
    <view class="search-header">
      <text class="search-keyword">"{{ keyword }}"</text>
      <text class="result-count">共找到 {{ filteredAndSortedCards.length }} 个结果</text>
    </view>

    <!-- 排序控件 -->
    <view class="sort-controls">
      <view 
        class="sort-option" 
        :class="{ active: currentSort === 'default' }"
        @click="setSort('default')"
      >
        综合排序
      </view>
      <view 
        class="sort-option" 
        :class="{ active: currentSort === 'price' }"
        @click="togglePriceSort"
      >
        价格排序
        <text v-if="currentSort === 'price'" class="sort-arrow">
          {{ priceSortOrder === 'desc' ? '↓' : '↑' }}
        </text>
      </view>
    </view>

    <!-- 结果列表 -->
    <!-- 垂直滚动容器：承载结果列表，占满剩余高度（flex:1），避免内容溢出 -->
    <scroll-view class="content" :scroll-y="true">
      <view class="grid">
        <!-- 循环渲染过滤+排序后的卡片数据：idx为临时索引（实际项目建议用card唯一ID），点击卡片跳转详情页 -->
        <view 
          v-for="(card, idx) in filteredAndSortedCards" 
          :key="idx" 
          class="card"
          @click="goToDetail(card)"
        >
          <view 
            class="media"
            :class="{ none: !card.image }"
            :style="card.image ? 'background-image: url(' + card.image + ')' : ''"
          ></view>
          <view class="body">
            <view class="title">{{ card.title }}</view>
            <view class="meta">
              <view class="user">
                <view class="avatar" :style="avatarStyle(card)">{{ (card.username || '').slice(0,1) }}</view>
                <view class="username">{{ card.username }}</view>
              </view>
              <view class="price">￥{{ card.price }}</view>
            </view>
          </view>
        </view>
        
        <view v-if="filteredAndSortedCards.length === 0" class="empty">
          <text>没有找到相关结果</text>
          <text class="empty-tip">换个关键词试试吧</text>
        </view>
      </view>
      
      <!-- 底部占位 -->
      <view class="bottom-placeholder"></view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      keyword: '',
      currentSort: 'default', // 'default' 或 'price'
      priceSortOrder: 'desc', // 'asc' 或 'desc'
      cards: [
        { title: '帮我搬一台空调（楼梯）', username: '小张', price: 150, image: 'https://images.unsplash.com/photo-1587829741301-dc798b83add3?auto=format&fit=crop&w=800&q=60' },
        { title: '代购：某专业考试复习资料（电子）', username: '米米', price: 20, image: '' },
        { title: '手机紧急维修：屏幕需要更换并同步数据（急）', username: '阿凯', price: 300, image: 'https://images.unsplash.com/photo-1510557880182-3f8a7f9b4f6d?auto=format&fit=crop&w=800&q=60' },
        { title: '小区帮取快递（需楼下取件）', username: '玲玲', price: 10, image: 'https://images.unsplash.com/photo-1546525848-3ce03ca516f6?auto=format&fit=crop&w=800&q=60' },
        { title: '阳台深度清洁（1小时）', username: '家政小王', price: 80, image: 'https://images.unsplash.com/photo-1503342452485-86f7f26d2f48?auto=format&fit=crop&w=800&q=60' },
        { title: '点餐并帮忙取餐（代付）', username: '小刘', price: 12, image: '' },
        { title: '帮忙照看宠物一整天', username: '李阿姨', price: 50, image: 'https://images.unsplash.com/photo-1543466835-00a7907e9de1?auto=format&fit=crop&w=800&q=60' },
        { title: '辅导小学数学作业', username: '大学生小王', price: 30, image: '' }
      ]
    }
  },
  
  computed: {
    filteredCards() {
      if (!this.keyword) return []
      
      const searchKey = this.keyword.toLowerCase()
      return this.cards.filter(card => 
        card.title.toLowerCase().includes(searchKey) || 
        card.username.toLowerCase().includes(searchKey) ||
        card.price.toString().includes(searchKey)
      )
    },

    filteredAndSortedCards() {
      // 先过滤卡片
      let result = [...this.filteredCards];
      
      // 如果是价格排序，则进行排序
      if (this.currentSort === 'price') {
        result.sort((a, b) => {
          if (this.priceSortOrder === 'asc') {
            return a.price - b.price;
          } else {
            return b.price - a.price;
          }
        });
      }
      
      return result;
    }
  },
  
  onLoad(options) {
    if (options.keyword) {
      this.keyword = decodeURIComponent(options.keyword)
    }
  },
  
  methods: {
    setSort(sortType) {
      this.currentSort = sortType;
    },

    togglePriceSort() {
      if (this.currentSort !== 'price') {
        // 第一次点击价格排序，默认降序
        this.currentSort = 'price';
        this.priceSortOrder = 'desc';
      } else {
        // 在升序和降序之间切换
        this.priceSortOrder = this.priceSortOrder === 'asc' ? 'desc' : 'asc';
      }
    },

    goToDetail(card) {
      const cardData = encodeURIComponent(JSON.stringify(card))
      uni.navigateTo({
        url: `/pages/index/detail?cardData=${cardData}`
      })
    },
    
    avatarStyle(card) {
      if (!card.username) return {}
      const colors = [
        'linear-gradient(135deg,#6dd5ed 0%,#2193b0 100%)',
        'linear-gradient(135deg,#f6d365 0%,#fda085 100%)',
        'linear-gradient(135deg,#a1c4fd 0%,#c2e9fb 100%)',
        'linear-gradient(135deg,#d4fc79 0%,#96e6a1 100%)'
      ]
      const index = card.username.charCodeAt(0) % colors.length
      return {
        background: colors[index],
        color: '#fff'
      }
    }
  }
}
</script>

<style scoped>
.search-result-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(180deg, #eef2ff 0%, #f8fafc 100%);
  box-sizing: border-box;
}

/* 顶部留空(暂不启用) */
/* .top-space {
  height: 54px;
  width: 100%;
} */

.search-header {
  padding: 16px;
  background: white;
  border-bottom: 1px solid #eef2ff;
  box-sizing: border-box;
}

.search-keyword {
  font-size: 18px;
  font-weight: bold;
  color: #16202b;
}

.result-count {
  font-size: 14px;
  color: #8b94a6;
  margin-left: 8px;
}

.sort-controls {
  display: flex;
  background: white;
  border-bottom: 1px solid #eef2ff;
  padding: 12px 16px;
}

.sort-option {
  flex: 1;
  text-align: center;
  padding: 8px;
  border-radius: 6px;
  color: #8b94a6;
  font-size: 14px;
}

.sort-option.active {
  background: #56BAEC;
  color: white;
  font-weight: bold;
}

.sort-arrow {
  margin-left: 4px;
  font-size: 12px;
}

.content {
  flex: 1;
  padding: 12px;
  box-sizing: border-box;
}

/* 网格布局 - 与首页保持一致 */
.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

/* 卡片样式 - 与首页保持一致 */
.card {
  background: #ffffff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 18px rgba(18, 24, 40, 0.06);
  cursor: pointer;
  transition: transform 0.18s ease, box-shadow 0.18s ease;
  display: flex;
  flex-direction: column;
}
.card:active {
  transform: translateY(-2px);
  box-shadow: 0 18px 36px rgba(18, 24, 40, 0.12);
}

.media {
  height: 160px;
  display: block;
  background: linear-gradient(0deg, rgba(0,0,0,0.16), rgba(0,0,0,0.02)), 
              url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="800" height="500"><rect width="100%" height="100%" fill="%23e6eef7"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="34" fill="%2399a6b8">图片预览</text></svg>') center/cover no-repeat;
  background-size: cover;
  background-position: center;
}
.media.none {
  height: 0;
  padding: 0;
}

.card .media.none + .body {
  justify-content: space-between;
  display: flex;
  flex-direction: column;
  padding-top: 12px;
  padding-bottom: 12px;
}

.card .media.none + .body .meta {
  margin-top: auto;
}

.body {
  padding: 10px 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.title {
  font-size: 15px;
  font-weight: 700;
  color: #16202b;
  line-height: 1.3;
  /* 文字超出显示省略号 */
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.price {
  background: linear-gradient(135deg, #6dd5ed 0%, #2193b0 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-weight: 800;
}

.user {
  display: flex;
  align-items: center;
  gap: 8px;
}

.avatar {
  width: 34px;
  height: 34px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-weight: 700;
  flex-shrink: 0;
}

.username {
  font-size: 13px;
  color: #8b94a6;
  /* 用户名超出显示省略号 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px;
}

.empty {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
  color: #8b94a6;
}

.empty-tip {
  display: block;
  margin-top: 8px;
  font-size: 14px;
}

/* 底部导航占位 */
.bottom-placeholder {
  height: 20px;
}
</style>